<template>
  <div class="container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.titleObj[state.dialog.type]"
      label-position="top" width="700px">
      <el-form ref="dialogFormRef" :model="state.ruleForm" :rules="state.ruleRules" label-width="auto">
        <el-form-item label="材料名称(中文):" prop="chinese_name">
          <el-input v-model="state.ruleForm.chinese_name" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="英文名称:" prop="english_name">
          <el-input v-model="state.ruleForm.english_name" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="内部名称:" prop="internal_name">
          <el-input v-model="state.ruleForm.internal_name" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <!-- <el-form-item label="地区类型:" prop="nationality">
          <el-radio-group v-model="state.ruleForm.nationality" :disabled="isDisabledFn">
            <el-radio :label="1">国内</el-radio>
            <el-radio :label="2">国外</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="材料介绍:" prop="material_desc">
          <el-input v-model="state.ruleForm.material_desc" placeholder="请输入" type="textarea" clearable
            :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="英文材料性能:" prop="abroad_material_desc">
          <el-input v-model="state.ruleForm.abroad_material_desc" placeholder="请输入" type="textarea" clearable
            :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="最大打印尺寸:" prop="print_size">
          <el-input v-model="state.ruleForm.print_size" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="启用:" prop="status">
          <el-radio-group v-model="state.ruleForm.status" :disabled="isDisabledFn">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="颜色:" prop="colour">
          <el-input v-model="state.ruleForm.colour" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="密度:" prop="accuracy">
          <el-input v-model="state.ruleForm.accuracy" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="基础厚度:" prop="thickness">
          <el-input v-model="state.ruleForm.thickness" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="发货交期:" prop="delivery_time">
          <el-checkbox-group v-model="state.ruleForm.delivery_time" @change="changeCheck">
            <el-checkbox v-for="item in deliveryArr" :key="item.id" :label="item.id" :value="item.id">
              <div class="flex_cen">
                <div class="mr5">{{ item.name }}</div>
                <!-- <el-icon @click.stop.prevent="delDeliv(item)"><Delete /></el-icon> -->
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div class="flex_cen_end mbfu15">
          <el-input v-if="isDelivAdd" v-model="deliveryTimeVale" type="number" style="width: 200px;margin-right: 20px;"
            placeholder="请输入" />
          <div class="cursors" @click="addOrEditDeliv">{{ isDelivAdd ? '保存' : '新增' }}</div>
        </div>
        <el-form-item v-for="item in priceArr" :key="item.id" :label="`${item.name}体积价`"
          :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
          <el-input v-model="item.price" type="number" placeholder="请输入" clearable :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="体积价:" prop="price">
          <el-input v-model="state.ruleForm.price" type="number" placeholder="请输入" clearable :disabled="isDisabledFn"   @input="handleNumberInput('price')" />
        </el-form-item>
        <el-form-item label="材料性能:" prop="performance">
          <el-input v-model="state.ruleForm.performance" placeholder="请输入" type="textarea" clearable
            :disabled="isDisabledFn" />
        </el-form-item>
         <el-form-item label="英文材料性能:" prop="abroad_performance">
          <el-input v-model="state.ruleForm.abroad_performance" placeholder="请输入" type="textarea" clearable
            :disabled="isDisabledFn" />
        </el-form-item>
        <el-form-item label="克重价:" prop="grammage_price">
          <el-input v-model="state.ruleForm.grammage_price" type="number" placeholder="请输入" clearable
            :disabled="isDisabledFn" @input="handleNumberInput('grammage_price')" />
        </el-form-item>
        <el-form-item label="英文克重价:" prop="abroad_grammage_price">
          <el-input v-model="state.ruleForm.abroad_grammage_price" type="number" placeholder="请输入" clearable
            :disabled="isDisabledFn" @input="handleNumberInput('abroad_grammage_price')" />
        </el-form-item>
        <el-form-item label="最低价:" prop="minimum_price">
          <el-input v-model="state.ruleForm.minimum_price" type="number" placeholder="请输入" clearable
            :disabled="isDisabledFn" @input="handleNumberInput('minimum_price')" />
        </el-form-item>
        <el-form-item label="父级:" prop="pid">
          <el-cascader v-model="state.ruleForm.pid" :options="pidArr" :show-all-levels="false"
            :props="{ checkStrictly: true, value: 'id', label: 'chinese_name' }" placeholder="请选择" style="width: 100%"
            clearable>
            <template #default="{ data }">
              <span>{{ data.chinese_name }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="增值服务:" prop="value_added_services">
          <el-checkbox-group v-model="state.ruleForm.value_added_services">
            <el-checkbox v-for="item in servicesArr" :key="item.id" :label="item.id" :value="item.id">
              <div class="flex_cen">
                <div class="mr5">{{ item.name }}</div>
                <el-icon @click.stop.prevent="delServe(item)">
                  <Delete />
                </el-icon>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序:" prop="sort">
          <el-input v-model="state.ruleForm.sort" type="number" placeholder="0" clearable :disabled="isDisabledFn"
            @input="handleNumberInput('sort')" />
        </el-form-item>

        <div class="flex_cen_end mbfu15">
          <el-input v-if="isAddService" v-model="serviceValue" style="width: 200px;margin-right: 20px;"
            placeholder="请输入" />
          <div class="cursors" @click="addOrEditSer">{{ isAddService ? '保存' : '新增' }}</div>
        </div>
        <el-form-item label="图片:" prop="sample_image">
          <div v-if="!isDisabledFn" class="up-file">
            <UploadFile v-model="state.ruleForm.sample_image" :value="state.ruleForm.sample_image"
              @uploadfile="onUploadHead" :limit="1" />
          </div>
          <div class="imgs">
            <img class="imgshow" v-for="(itom, indox) in state.ruleForm.sample_image" :src="itom.url" :key="indox" />
          </div>
        </el-form-item>
      </el-form>
      <template v-if="!isDisabledFn" #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" size="default" @click="onSubmit">保 存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="addMaterialIndex">
import { Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { defineAsyncComponent, reactive, onMounted, computed, ref } from 'vue';
import {
  materialList, deliveryTime, delDeliveryTime, addDeliveryTime, addedservicesIndex, addedservicesAdd,
  addedservicesDel, materialAdd, materialDetail, materialEdit,
} from '/@/api/startfab/index';
import { accountTypeArr, accountStatusArr } from '/@/commmon/variate';
const UploadFile = defineAsyncComponent(() => import('/@/components/Upload/file.vue'));
const emit = defineEmits(['updateList']);
const state = reactive({
  accountTypeArr: accountTypeArr,
  accountStatusArr: accountStatusArr,
  ruleForm: {
    chinese_name: '',
    nationality: '',
    material_desc: '',
    print_size: '',
    status: '',
    colour: '',
    accuracy: '',
    thickness: '',
    delivery_time: [],
    price: '',
    performance: '',
    abroad_performance: '',
    abroad_material_desc: '',
    grammage_price: '',
    abroad_grammage_price: '',
    minimum_price: '',
    pid: [],
    value_added_services: [],
    sample_image: []
  },
  ruleRules: {
    chinese_name: [{ required: true, message: '必填', trigger: 'blur' }],
    english_name: [{ required: true, message: '必填', trigger: 'blur' }],
    nationality: [{ required: true, message: '必填', trigger: 'blur' }],
    material_desc: [{ required: true, message: '必填', trigger: 'blur' }],
    print_size: [{ required: true, message: '必填', trigger: 'blur' }],
    status: [{ required: true, message: '必填', trigger: 'blur' }],
    colour: [{ required: true, message: '必填', trigger: 'blur' }],
    accuracy: [{ required: true, message: '必填', trigger: 'blur' }],
    thickness: [{ required: true, message: '必填', trigger: 'blur' }],
    delivery_time: [{ required: true, message: '必填', trigger: 'blur' }],
    price: [{ required: true, message: '必填', trigger: 'blur' }],
    performance: [{ required: true, message: '必填', trigger: 'blur' }],
    abroad_performance: [{ required: true, message: '必填', trigger: 'blur' }],
    abroad_material_desc: [{ required: true, message: '必填', trigger: 'blur' }],
    grammage_price: [{ required: true, message: '必填', trigger: 'blur' }],
    abroad_grammage_price: [{ required: true, message: '必填', trigger: 'blur' }],
    minimum_price: [{ required: true, message: '必填', trigger: 'blur' }],
    pid: [{ required: true, message: '必填', trigger: 'blur' }],
    value_added_services: [{ required: true, message: '必填', trigger: 'blur' }],
    sample_image: [{ required: true, message: '必填', trigger: 'blur' }]
  },
  dialog: {
    isShowDialog: false,
    row: null,
    type: '',
    titleObj: {
      'view': '查看',
      'edit': '编辑',
      'add': '新增'
    },
    isDisabled: false
  },
  loading: false
})
const handleNumberInput = (field) => {
  const value = state.ruleForm[field];
  // 处理空值（清空时允许为空，提交时再校验）
  if (value === null || value === '' || value === undefined) {
    return;
  }
  // 转换为数字，若小于0则强制设为0
  const numValue = Number(value);
  if (numValue < 0) {
    state.ruleForm[field] = 0;
  }
};
const onUploadHead = (data) => {
  state.ruleForm.sample_image = []
  if (data.length) {
    const resData = data[0].response
    resData.data.forEach((item) => {
      state.ruleForm.sample_image.push({
        name: item.oss_upload_files_path ? extractFileNam(item.oss_upload_files_path) : '',
        url: item.oss_upload_files_path
      })
    })
  }
}
const extractFileNam = (url) => {
  const match = url.match(/\/([^/]+)\.\w+$/);
  return match ? match[1] : null;
}
const deliveryArr = ref([])
const priceArr = ref()
const getItemsById = (data, ids) => {
  return data.filter(item => ids.includes(item.id));
}
const changeCheck = (val) => {
  const arr1 = JSON.parse(JSON.stringify(getItemsById(deliveryArr.value, val)))
  const arr2 = JSON.parse(JSON.stringify(priceArr.value))
  if (arr1.length < arr2.length) {
    const delArr = findDiffIds(arr2, arr1)
    const index = arr2.findIndex(item => item.id == delArr[0])
    if (index !== -1) {
      priceArr.value.splice(index, 1)
    }
  } else {
    const merged = [...arr1, ...arr2].reduce((acc, item) => {
      acc[item.id] = item;
      return acc;
    }, {})
    const result = Object.values(merged)
    priceArr.value = result
  }
}
const isDelivAdd = ref(false)
const deliveryTimeVale = ref('')
const addOrEditDeliv = async () => {
  if (isDelivAdd.value) {
    if (deliveryTimeVale.value) {
      const resData = await addDeliveryTime({ name: deliveryTimeVale.value })
      if (resData.code == 10000) {
        deliveryTimeFn()
        deliveryTimeVale.value = ''
        isDelivAdd.value = false
      }
    } else {
      ElMessage('请输入')
    }
  } else {
    isDelivAdd.value = true
  }
}
const delDeliv = async (val) => {
  const resData = await delDeliveryTime({ id: val.id })
  if (resData.code == 10000) {
    const arr1 = JSON.parse(JSON.stringify(state.ruleForm.delivery_time))
    const index1 = arr1.findIndex(item => item.id == val.id)
    if (index1 !== -1) {
      state.ruleForm.delivery_time.splice(index1, 1)
    }
    const arr2 = JSON.parse(JSON.stringify(priceArr.value))
    const index2 = arr2.findIndex(item => item.id == val.id)
    if (index2 !== -1) {
      priceArr.value.splice(index2, 1)
    }
    deliveryTimeFn()
  }
}
const servicesArr = ref([])
const isAddService = ref(false)
const serviceValue = ref('')
const addOrEditSer = async () => {
  if (isAddService.value) {
    if (serviceValue.value) {
      const resData = await addedservicesAdd({ name: serviceValue.value })
      if (resData.code == 10000) {
        serviceFn()
        serviceValue.value = ''
        isAddService.value = false
      }
    } else {
      ElMessage('请输入')
    }
  } else {
    isAddService.value = true
  }
}
const delServe = async (val) => {
  const resData = await addedservicesDel({ id: val.id })
  if (resData.code == 10000) {
    serviceFn()
  }
}
const serviceFn = async () => {
  const arr1 = []
  const resData = await addedservicesIndex()
  if (resData.code === 10000) {
    const list = resData.data.list
    if (list.length) {
      list.forEach((item) => {
        arr1.push({
          ...item,
          id: String(item.id)
        })
      })
    }
    if (!servicesArr.value.length) {
      servicesArr.value = arr1
    } else {
      const delArr = findDiffIds(servicesArr.value, arr1)
      if (servicesArr.value.length > arr1.length) {
        const index = servicesArr.value.findIndex(item => item.id == delArr[0])
        if (index !== -1) {
          servicesArr.value.splice(index, 1)
        }
      } else if (servicesArr.value.length < arr1.length) {
        const rowObj = list[list.length - 1]
        servicesArr.value.push(rowObj)
      }
    }
    servicesArr.value = [...new Map(servicesArr.value.map(item => [item.id, item])).values()]
  }
}
const pidArr = ref([])
const getSelect1 = () => {
  const params = {
    page: 1,
    pageNum: 10000,
  }
  materialList(params).then((res) => {
    if (res.code === 10000) {
      pidArr.value = [
        {
          id: 0,
          chinese_name: '无',
          children: res.data
        }
      ]
    }
  })
}
const deliveryTimeFn = async () => {
  const arr1 = []
  const resData = await deliveryTime()
  if (resData.code === 10000) {
    const list = resData.data.list
    if (list.length) {
      list.forEach((item) => {
        arr1.push({
          ...item,
          id: String(item.id)
        })
      })
    }
    if (!deliveryArr.value.length) {
      deliveryArr.value = arr1
    } else {
      const delArr = findDiffIds(deliveryArr.value, arr1)
      console.log()
      if (deliveryArr.value.length > arr1.length) {
        const index = deliveryArr.value.findIndex(item => item.id == delArr[0])
        if (index !== -1) {
          deliveryArr.value.splice(index, 1)
        }
      } else if (deliveryArr.value.length < arr1.length) {
        const rowObj = list[list.length - 1]
        deliveryArr.value.push(rowObj)
      }
    }
  }
}
const findDiffIds = (arr1, arr2) => {
  const ids1 = new Set(arr1.map(item => item.id))
  const ids2 = new Set(arr2.map(item => item.id))
  const diff = []
  for (let id of ids2) {
    if (!ids1.has(id)) diff.push(id)
  }
  for (let id of ids1) {
    if (!ids2.has(id)) diff.push(id)
  }
  return diff
}
const dialogFormRef = ref('dialogFormRef')
const openDialog = (type, row) => {
  const typeArr = ['edit', 'view']
  state.dialog.row = row
  state.dialog.type = type
  getSelect1()
  deliveryTimeFn()
  serviceFn()
  closeDialog()
  if (typeArr.includes(type)) {
    getViewDetail(row)
  }
  setTimeout(() => {
    state.dialog.isShowDialog = true;
    setTimeout(() => {
      dialogFormRef.value && dialogFormRef.value.clearValidate()
    })
  }, 1000)
};
const onSubmit = async () => {
  dialogFormRef.value.validate(async (valid) => {
    if (valid) {
      const formData = JSON.parse(JSON.stringify(state.ruleForm))
      const params = {
        ...formData,
        delivery_time: formData.delivery_time.join(','),
        value_added_services: formData.value_added_services.join(','),
        sample_image: formData.sample_image.length ? formData.sample_image[0].url : '',
        pid: formData.pid[formData.pid.length - 1],
        times_price: JSON.stringify(priceArr.value)
      }
      if (state.dialog.type == 'add') {
        const resData = await materialAdd(params)
        if (resData.code == 10000) {
          state.dialog.isShowDialog = false;
          emit('updateList')
        }
      } else if (state.dialog.type == 'edit') {
        const resData = await materialEdit(params)
        if (resData.code == 10000) {
          state.dialog.isShowDialog = false;
          emit('updateList')
        }
      }
    }
  })
}
const getViewDetail = async (row) => {
  const resData = await materialDetail({ id: row.id })
  if (resData.code == 10000) {
    state.ruleForm = {
      ...resData.data,
      delivery_time: resData.data.delivery_time ? resData.data.delivery_time.split(',') : [],
      value_added_services: resData.data.value_added_services ? resData.data.value_added_services.split(',') : [],
      sample_image: resData.data.sample_image ? [{
        name: resData.data.sample_image ? extractFileNam(resData.data.sample_image) : '',
        url: resData.data.sample_image
      }] : [],
    }
    priceArr.value = resData.data.times_price.length ? JSON.parse(resData.data.times_price) : []
  }
}
const closeDialog = () => {
  state.ruleForm = {
    chinese_name: '',
    nationality: '',
    material_desc: '',
    print_size: '',
    status: '',
    colour: '',
    accuracy: '',
    thickness: '',
    delivery_time: [],
    price: '',
    performance: '',
    abroad_performance: '',
    abroad_material_desc: '',
    grammage_price: '',
    abroad_grammage_price: '',
    minimum_price: '',
    pid: [],
    value_added_services: [],
    sample_image: []
  }
  priceArr.value = []
  isAddService.value = false
  isDelivAdd.value = false
};
const onCancel = () => {
  closeDialog();
  state.dialog.isShowDialog = false;
};
onMounted(() => { })
const isDisabledFn = computed(() => {
  return state.dialog.type === 'view'
})
defineExpose({
  openDialog,
})
</script>
<style scoped lang="scss">
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-form-item__content) {
  display: block;
}

:deep(.el-dialog__body) {
  max-height: 500px !important;
}

.flex_cen {
  display: flex;
  align-items: center;
}

.flex_cen_end {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.mr5 {
  margin-right: 5px;
}

.cursors {
  cursor: pointer;
  color: #409EFF;
}

.mbfu15 {
  position: relative;
  z-index: 9;
  margin-bottom: 5px;
  margin-top: -15px;
}
.imgshow {
  width: 100px;
  height: 100px;
}
</style>
